package com.spring.cloud.microservicehystrix8001.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.spring.api.entities.Dept;
import com.spring.cloud.microservicehystrix8001.service.DeptService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.SocketTimeoutException;
import java.util.List;

@RestController
public class DeptController {

    @Resource
    private DeptService deptService;

    @Resource
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    //一旦调用出现异常，会自动调用@HystrixCommand标注好的fallbackMethod调用类中定义好的方法
    @HystrixCommand(fallbackMethod = "dealNullRunTime")
    public Dept get(@PathVariable("id") String id) {
        Dept dept = deptService.get(id);
        if (dept == null) {
            throw new RuntimeException("该部门不存在");
        }
        return dept;
    }

    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public Boolean add(@RequestBody Dept dept) {
        return deptService.add(dept);
    }

    @RequestMapping(value = "/dept/findAll", method = RequestMethod.GET)
    public List<Dept> findAll() {
        return deptService.findAll();
    }

    /**
     * 部门服务发现
     *
     * @return
     */
    @RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
    public Object findDept() {
        List<String> list = discoveryClient.getServices();
        list.forEach(System.out::println);
//        查询服务中是否有包含 PROVIDER_8001 服务名
        List<ServiceInstance> serviceList = discoveryClient.getInstances("PROVIDER_8001");
        for (ServiceInstance service : serviceList) {
            System.out.println(service.getInstanceId() + "\t" + service.getHost() + "\t" + service.getPort() + "\t" + service.getUri());
        }
        return this.discoveryClient;
    }

    public Dept dealNullRunTime(@PathVariable("id") String id) {
        Dept dept = new Dept(id, "该部门不存在", "该数据库不存在");
        return dept;
    }
}
